package com.shu.qq.config.security.jwt;

import com.shu.qq.data.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
@Slf4j
public class AuthenticationService {
    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录认证获取登录用户
     * @param account 用户名
     * @param password 密码
     * @return 结果
     */
    public User login(String account, String password)  {
        // 用户认证
        Authentication authentication = null;
//        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new
                    UsernamePasswordAuthenticationToken(account, password);//使用用户名和密码验证Token
            //认证过程中会调用UserDetailsService#loadUserByUsername方法获取用户信息，并且封装到authentication的principal中
            authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken); //生成认证，交给SecurityContext保存
//        }
        //中间认证失败会调用失败的处理器
//        catch (Exception e) {
//            return null;
//        }
        User loginUser = (User) authentication.getPrincipal(); //拿到loadUserByUsername中获得到的User
        return loginUser; //返回获取到的用户信息
    }

}
